package com.baitiaojun.repeatsubmit.core.interceptor;

import com.baitiaojun.common.domain.model.result.CommonResult;
import com.baitiaojun.common.utils.servlet.ServletUtils;
import com.baitiaojun.repeatsubmit.core.annotation.SubmitRepeat;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface RepeatSubmitInterceptor extends HandlerInterceptor {

    @Override
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            SubmitRepeat submitRepeat = ((HandlerMethod) handler).getMethod().getAnnotation(SubmitRepeat.class);
            if (submitRepeat == null) {
                return true;
            }
            if (isRepeatable(submitRepeat.interval(), submitRepeat.tokenSign(), request)) {
                ServletUtils.render(response, CommonResult.ok(submitRepeat.message()));
                return false;
            }
        }
        return true;
    }

    boolean isRepeatable(Long interval, String token, HttpServletRequest request);
}
